package com.edata.bigdata.flink;

import org.apache.flink.api.common.serialization.DeserializationSchema;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class JsonDeserializationSchema<T> implements DeserializationSchema<T> {
    public Logger logger = LoggerFactory.getLogger(this.getClass());
    private final Class<T> targetClass;
    private static final ObjectMapper mapper = new ObjectMapper();

    public JsonDeserializationSchema(Class<T> targetClass) {
        this.targetClass = targetClass;
    }

    @Override
    public T deserialize(byte[] bytes) throws IOException {
        if (bytes == null || bytes.length == 0) {
            return null;
        }
        String jsonStr = new String(bytes, StandardCharsets.UTF_8)
                .replaceAll("[\\p{Cntrl}&&[^\\r\\n\\t]]", "")
                .trim();
        if (jsonStr.isEmpty() || jsonStr.equals("null")) {
            return null;
        }
        try {
            return mapper.readValue(bytes, targetClass);
        } catch (Exception e) {
            logger.warn("JSON 解析失败，跳过消息：{}", jsonStr);
            return null;
        }
    }

    @Override
    public boolean isEndOfStream(T t) {
        return false;
    }

    @Override
    public TypeInformation<T> getProducedType() {
        return TypeInformation.of(targetClass);
    }
}
